import json
import os
import random
from datetime import datetime
from pathlib import Path
from django.db.models import ExpressionWrapper, F, IntegerField
from datetime import timedelta

from django.shortcuts import get_object_or_404
from django.utils import timezone


from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, Count, Sum
from rest_framework import filters

from apps.common.models import Pagination
from apps.data.schemas import *
from apps.pbi.filters import Pbi_Common_PdfsFilter, BusinessOpportunityFilter, ContractFilter, OrderFilter
from apps.pbi.models import Pbi_Common_Pdfs, BusinessOpportunity, Status_change, Progress_thisweek, Contract, \
    Contract_Common_Pdfs, Order
from apps.pbi.serializers import Pbi_Common_PdfsSerializer, BusinessOpportunitySerializer, \
    BusinessOpportunitySigning_PredictionSerializer, ContractSerializer, Contract_Common_PdfsSerializer, OrderSerializer
from apps.system.models import User, Check, Workflow, Dict_item
from apps.system.serializers import WorkflowSerializer
from extensions.common.schema import *
from extensions.common.base import *
from extensions.permissions import *
from extensions.exceptions import *
from extensions.viewsets import *
from apps.pbi.filters import *
from apps.pbi.models import *
from apps.pbi.permissions import PbiPermission
from apps.pbi.serializers import *
from tools.func import get_model_fullname


class PbiClientsCheckFlowViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """客户"""
    model = CheckFlow
    serializer_class = CheckFlowSerializer
    permission_classes = [IsAuthenticated, PbiPermission]
    filterset_fields = ['name']
    search_fields = ['name']
    ordering = ['id']
    # queryset = model.objects.all()
    id = ContentType.objects.get_for_model(Client).id
    queryset = CheckFlow.objects.filter(Q(model=id))


class ClientViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """客户"""
    serializer_class = ClientSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = ClientFilter
    search_fields = ['number', 'name']
    select_related_fields = ['company', 'creator','updater','next_checker']
    ordering_fields = ['id', 'number', 'name','create_time','update_time']
    ordering = ['id']

    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)
        return Client.objects.filter(base_query)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Client').first()

        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)

    @transaction.atomic
    def perform_create(self,serializer):
        client = serializer.save()
        content_type = ContentType.objects.get_for_model(client)
        Check.objects.create(
            content_type=content_type, object_id=client.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        # client.client_check.add(client_check)

    @transaction.atomic
    def perform_update(self, serializer):
        client = serializer.save()
        content_type = ContentType.objects.get_for_model(client)
        Check.objects.create(
            content_type=content_type, object_id=client.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        client = self.get_object()
        # Set the new values
        client.step = request.data.get('step', client.step)
        client.is_effective = request.data.get('is_effective', client.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            client.next_checker = next_checker

        client.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(client)
        Check.objects.create(
            content_type=content_type, object_id=client.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Client.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def export(self, request, *args, **kwargs):
        """导出"""

        # return self.get_export_response(ClientImportExportSerializer)
        return self.get_export_response(ClientExportSerializer)

    @extend_schema(responses={200: DownloadResponse})
    @action(detail=False, methods=['get'])
    def import_template(self, request, *args, **kwargs):
        """导入模板"""

        return self.get_template_response(ClientImportExportSerializer)

    @extend_schema(request=UploadRequest, responses={204: None})
    @action(detail=False, methods=['post'])
    @transaction.atomic
    def import_data(self, request, *args, **kwargs):
        """导入数据"""

        request_serializer = UploadRequest(data=request.data)
        request_serializer.is_valid(raise_exception=True)
        validated_data = request_serializer.validated_data

        import_serializer = self.load_data(validated_data['file'], ClientImportExportSerializer)
        if not import_serializer.is_valid(raise_exception=False):
            raise ValidationError('数据错误')

        client_items = import_serializer.validated_data
        number = {item['number'] for item in client_items}
        # client_set = Client.objects.filter(number__in=number, team=self.company)
        client_set = Client.objects.all()

        create_client_set = []
        update_client_set = []
        for client_item in client_items:
            # client_item['company'] = self.company
            client_item['filled_by'] = self.user
            client_item['company'] = self.user.company
            client_item['step'] = 3 #导入的数据默认填报步骤已完成
            client_item['is_effective'] = 1 #导入的数据默认为已生效
            cooperation_attribute = client_item.pop('cooperation_attribute')
            cooperation_types = client_item.pop('cooperation_types')
            for client in client_set:
                if client.number == client_item['number']:
                    c = Client.objects.update(**client_item)
                    ca = json.loads(cooperation_attribute)
                    ct = json.loads(cooperation_types)
                    c.cooperation_attribute.set(ca)
                    c.cooperation_types.set(ct)
                    update_client_set.append(client)
                    for key, value in client_item.items():
                        setattr(client, key, value)
                    break
            else:
                c=Client.objects.create(**client_item)
                ca=json.loads(cooperation_attribute)
                ct=json.loads(cooperation_types)
                c.cooperation_attribute.set(ca)
                c.cooperation_types.set(ct)

        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Client.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Client.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)


class ManufactorViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """厂家"""
    serializer_class = SupplierManufactorSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = ManufactorFilter
    search_fields = ['number', 'name']
    select_related_fields = ['company', 'creator','updater','next_checker']
    ordering_fields = ['id', 'number', 'name','is_effective','create_time']

    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)
        return SupplierManufactor.objects.filter(base_query)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Client').first()

        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)

    @transaction.atomic
    def perform_create(self,serializer):
        manufactor = serializer.save()
        content_type = ContentType.objects.get_for_model(manufactor)
        Check.objects.create(
            content_type=content_type, object_id=manufactor.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    @transaction.atomic
    def perform_update(self, serializer):
        manufactor = serializer.save()
        content_type = ContentType.objects.get_for_model(manufactor)
        Check.objects.create(
            content_type=content_type, object_id=manufactor.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        manufactor = self.get_object()
        # Set the new values
        manufactor.step = request.data.get('step', manufactor.step)
        manufactor.is_effective = request.data.get('is_effective', manufactor.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            manufactor.next_checker = next_checker

        manufactor.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(manufactor)
        Check.objects.create(
            content_type=content_type, object_id=manufactor.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = SupplierManufactor.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = SupplierManufactor.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = SupplierManufactor.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)


class Pbi_CommonPdfsViewSet(ModelViewSet):
    """Pbi公共pdf"""

    serializer_class = Pbi_Common_PdfsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Pbi_Common_PdfsFilter
    search_fields = ['company__name', 'name']
    select_related_fields = ['company', 'creator']
    ordering_fields = ['id', 'name', 'create_time']
    queryset = Pbi_Common_Pdfs.objects.all()

    @transaction.atomic
    def perform_destroy(self, instance):
        instance.file.delete(save=False)
        instance.delete()
        Response(status=status.HTTP_204_NO_CONTENT)


class IntegratorViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """集成商"""
    model = SupplierIntegrator
    serializer_class = SupplierIntegratorSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = SupplierIntegratorFilter
    search_fields = ['number', 'name', 'phone', 'contact', 'remark','business_scope',
        'business_qualification']
    select_related_fields = ['company', 'creator','updater', 'next_checker']
    ordering_fields = ['id', 'number', 'name','is_effective','add_time']


    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)
        return SupplierIntegrator.objects.filter(base_query)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='Client').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)

    @transaction.atomic
    def perform_create(self,serializer):
        supplierIntegrator = serializer.save()
        content_type = ContentType.objects.get_for_model(supplierIntegrator)
        Check.objects.create(
            content_type=content_type, object_id=supplierIntegrator.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    @transaction.atomic
    def perform_update(self, serializer):
        supplierIntegrator = serializer.save()
        content_type = ContentType.objects.get_for_model(supplierIntegrator)
        Check.objects.create(
            content_type=content_type, object_id=supplierIntegrator.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        supplierIntegrator = self.get_object()
        # Set the new values
        supplierIntegrator.step = request.data.get('step', supplierIntegrator.step)
        supplierIntegrator.is_effective = request.data.get('is_effective', supplierIntegrator.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            supplierIntegrator.next_checker = next_checker

        supplierIntegrator.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(supplierIntegrator)
        Check.objects.create(
            content_type=content_type, object_id=supplierIntegrator.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = SupplierIntegrator.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        # query = Q(is_effective=-1) & Q(del_flag=0)
        queryset = SupplierIntegrator.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = SupplierIntegrator.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)


class ProductViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """产品"""
    serializer_class = ManufactorProductSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = ManufactorProductFilter
    search_fields = ['number', 'name', 'product_model', 'supplier_manufactor__name']
    select_related_fields = ['company', 'creator','updater','supplier_manufactor']
    ordering_fields = ['id', 'number', 'name','product_price','add_time']

    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)

        return ManufactorProduct.objects.filter(base_query)

    @transaction.atomic
    def perform_create(self, serializer):
        manufactor = serializer.save()
        content_type = ContentType.objects.get_for_model(manufactor)
        Check.objects.create(
            content_type=content_type, object_id=manufactor.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    @transaction.atomic
    def perform_update(self, serializer):
        manufactor = serializer.save()
        content_type = ContentType.objects.get_for_model(manufactor)
        Check.objects.create(
            content_type=content_type, object_id=manufactor.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = ManufactorProduct.objects.filter(id__in=selected_ids).update(del_flag=True)
        result = {"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)


class BusinessOpportunityViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """商机管理"""
    serializer_class = BusinessOpportunitySerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = BusinessOpportunityFilter
    search_fields = ['number', 'name']
    select_related_fields = ['company', 'creator','updater','next_checker']
    ordering_fields = ['id', 'number', 'name','is_effective','introduction_time','create_time','days_since_update','status_change_last_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return BusinessOpportunity.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)

        business_opportunities = BusinessOpportunity.objects.filter(base_query)
        business_opportunities = business_opportunities.annotate(
            days_since_update=ExpressionWrapper(
                (timezone.now() - F('update_time')), output_field=IntegerField()
            )
        )
        return business_opportunities
        # # 从请求参数中获取排序方式
        # order = self.request.query_params.get('order', 'asc')
        #
        # if order.lower() == 'desc':
        #     return business_opportunities.order_by('-days_since_update')
        # else:
        #     return business_opportunities.order_by('days_since_update')

    def list(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        statistic = queryset.aggregate(count=Count('id'),
                                       total_budget=Sum('budget'))
        serializer = self.get_serializer(queryset, many=True)
        data={
            "count": statistic['count'],
            "total_budget": round(statistic['total_budget']/10000, 2) if statistic['total_budget'] is not None else 0,
            "results":serializer.data
        }
        return Response(data=data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='BusinessOpportunity').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)

    #创建签约合同
    def create_contract(self, business_opportunity, project_status):
        if project_status.name == '签约项目':
            Contract.objects.create(
                business_opportunity=business_opportunity,
                company=self.user.company,
                step=0,
                is_effective=0,
                creator=self.request.user
            )

    @transaction.atomic
    def perform_create(self,serializer):
        business_opportunity = serializer.save()
        content_type = ContentType.objects.get_for_model(business_opportunity)
        Check.objects.create(
            content_type=content_type, object_id=business_opportunity.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        project_status_id = self.request.data.get('project_status', '')
        project_status = Dict_item.objects.get(id=project_status_id)
        Status_change.objects.create(
            business_opportunity=business_opportunity, project_status=project_status,
            creator=self.request.user
        )
        self.create_contract(business_opportunity, project_status)
        progress_thisweek = self.request.data.get('progress_thisweek', None)
        if progress_thisweek:
            Progress_thisweek.objects.create(
                business_opportunity=business_opportunity, progress_record=progress_thisweek,
                creator=self.request.user
            )


    @transaction.atomic
    def perform_update(self, serializer):
        # 获取原始的商机对象
        original_business_opportunity = self.get_object()

        # 获取原始的 project_status
        old_project_status = original_business_opportunity.project_status

        # 保存更新后的商机对象
        business_opportunity = serializer.save()
        content_type = ContentType.objects.get_for_model(business_opportunity)
        Check.objects.create(
            content_type=content_type, object_id=business_opportunity.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

        # 检查 project_status 是否发生变化
        new_project_status_id = self.request.data.get('project_status', '')
        if new_project_status_id:
            new_project_status = Dict_item.objects.get(id=new_project_status_id)
            if new_project_status != old_project_status:
                Status_change.objects.create(
                    business_opportunity=business_opportunity, project_status=new_project_status,
                    creator=self.request.user
                )
                self.create_contract(business_opportunity, new_project_status)
        progress_thisweek = self.request.data.get('progress_thisweek', None)
        if progress_thisweek:
            Progress_thisweek.objects.create(
                business_opportunity=business_opportunity, progress_record=progress_thisweek,
                creator=self.request.user,

            )


    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        business_opportunity = self.get_object()
        # Set the new values
        business_opportunity.step = request.data.get('step', business_opportunity.step)
        business_opportunity.is_effective = request.data.get('is_effective', business_opportunity.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            business_opportunity.next_checker = next_checker
        else:
            business_opportunity.next_checker = None

        business_opportunity.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(business_opportunity)
        Check.objects.create(
            content_type=content_type, object_id=business_opportunity.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = BusinessOpportunity.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = BusinessOpportunity.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = BusinessOpportunity.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)


class OrderViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """订单管理"""
    serializer_class = OrderSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = OrderFilter
    search_fields = ['number', 'name','contract__number','contract__name','contract__business_opportunity__number','contract__business_opportunity__name']
    select_related_fields = ['company', 'creator','updater','next_checker']
    ordering_fields = ['id', 'number', 'name','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return Order.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)

        orders = Order.objects.filter(base_query)

        return orders


    @action(detail=False, methods=['get'])
    #获取是否有相同的number
    def getSameNumber(self, request):
        number = request.query_params.get('number')
        id = request.GET.get('id', None)
        # 如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Order.objects.exclude(id=id).filter(number=number).exists()
        else:
            exists = Order.objects.filter(number=number).exists()
        return Response(data=exists, status=status.HTTP_200_OK)

    def list(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        statistic = queryset.aggregate(count=Count('id'),
                                       total_order_amount=Sum('order_amount'),
                                       total_order_amount_notax=Sum('order_amount_notax'),
                                       )
        serializer = self.get_serializer(queryset, many=True)
        data={
            "count": statistic['count'],
            "total_order_amount": round(statistic['total_order_amount']/10000, 2) if statistic['total_order_amount'] is not None else 0,
            "total_order_amount_notax": round(statistic['total_order_amount_notax']/10000, 2) if statistic['total_order_amount_notax'] is not None else 0,
            "results":serializer.data
        }
        return Response(data=data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='BusinessOpportunity').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)


    @transaction.atomic
    def perform_create(self,serializer):
        order = serializer.save()
        content_type = ContentType.objects.get_for_model(order)
        Check.objects.create(
            content_type=content_type, object_id=order.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    @transaction.atomic
    def perform_update(self, serializer):
        order = serializer.save()# 保存订单
        content_type = ContentType.objects.get_for_model(order)
        Check.objects.create(
            content_type=content_type, object_id=order.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        order = self.get_object()
        # Set the new values
        order.step = request.data.get('step', order.step)
        order.is_effective = request.data.get('is_effective', order.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            order.next_checker = next_checker
        else:
            order.next_checker = None

        order.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(order)
        Check.objects.create(
            content_type=content_type, object_id=order.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Order.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Order.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Order.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)


class Contract_Common_PdfsViewSet(ModelViewSet):
    """Contract公共pdf"""

    serializer_class = Contract_Common_PdfsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = ['company__name', 'name']
    select_related_fields = ['company', 'creator']
    ordering_fields = ['id', 'name', 'add_time']
    queryset = Contract_Common_Pdfs.objects.all()

    @transaction.atomic
    def perform_destroy(self, instance):
        instance.file.delete(save=False)
        instance.delete()
        Response(status=status.HTTP_204_NO_CONTENT)


class ContractViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """签约合同管理"""
    serializer_class = ContractSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = ContractFilter
    search_fields = ['number', 'name','business_opportunity__name','business_opportunity__number']
    select_related_fields = ['company', 'creator','updater','next_checker']
    ordering_fields = ['id', 'number', 'name','is_effective','create_time']
    #
    # def get_queryset(self):
    #     base_query = Q(del_flag=False)
    #     # 根据权限添加额外的查询条件
    #     if "pbi_view_qs" not in self.request.user.permissions:
    #         base_query &= Q(company=self.request.user.company)
    #     return BusinessOpportunity.objects.filter(base_query)
    def get_queryset(self):
        base_query = Q(del_flag=False)
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)

        contracts = Contract.objects.filter(base_query)

        return contracts
        # # 从请求参数中获取排序方式
        # order = self.request.query_params.get('order', 'asc')
        #
        # if order.lower() == 'desc':
        #     return business_opportunities.order_by('-days_since_update')
        # else:
        #     return business_opportunities.order_by('days_since_update')

    def list(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        statistic = queryset.aggregate(count=Count('id'),
                                       total_contract_amount=Sum('contract_amount'),
                                       total_contract_amount_notax=Sum('contract_amount_notax'),
                                       )
        serializer = self.get_serializer(queryset, many=True)
        data={
            "count": statistic['count'],
            "total_contract_amount": round(statistic['total_contract_amount']/10000, 2) if statistic['total_contract_amount'] is not None else 0,
            "total_contract_amount_notax": round(statistic['total_contract_amount_notax']/10000, 2) if statistic['total_contract_amount_notax'] is not None else 0,
            "results":serializer.data
        }
        return Response(data=data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def workflow(self, request):
        workflow = Workflow.objects.filter(model_name='BusinessOpportunity').first()
        if workflow:
            workflow_serializer = WorkflowSerializer(workflow)
            return Response(workflow_serializer.data)

        else:
            return Response({"detail": "No workflow found for this object type."}, status=404)

    @action(detail=False, methods=['get'])
    #获取是否有相同的business_opportunity
    def getSameBusinessOpportunity(self, request):
        business_opportunity = request.query_params.get('business_opportunity')
        id = request.GET.get('id', None)
        # 如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Contract.objects.exclude(id=id).filter(business_opportunity=business_opportunity).exists()
        else:
            exists = Contract.objects.filter(business_opportunity=business_opportunity).exists()
        return Response(data=exists, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    #获取是否有相同的number
    def getSameNumber(self, request):
        number = request.query_params.get('number')
        id = request.GET.get('id', None)
        # 如果id不为空，说明是修改，需要排除自身
        if id is not None and id != '':
            exists = Contract.objects.exclude(id=id).filter(number=number).exists()
        else:
            exists = Contract.objects.filter(number=number).exists()
        return Response(data=exists, status=status.HTTP_200_OK)

    @transaction.atomic
    def perform_create(self, serializer):
        business_opportunity = serializer.validated_data.get('business_opportunity')

        # Assume Dict_item has a string field 'code'
        project_status = get_object_or_404(Dict_item, id='pbi0009_003')
        business_opportunity.project_status = project_status
        business_opportunity.update_time = timezone.now()  # Set update_time to current time
        business_opportunity.updater = self.request.user  # Set updater to current user
        Status_change.objects.create(
            business_opportunity=business_opportunity, project_status=project_status,
            creator=self.request.user
        )
        business_opportunity.save()

        contract = serializer.save()

        content_type = ContentType.objects.get_for_model(contract)
        Check.objects.create(
            content_type=content_type, object_id=contract.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )

    #审核
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        contract = self.get_object()
        # Set the new values
        contract.step = request.data.get('step', contract.step)
        contract.is_effective = request.data.get('is_effective', contract.is_effective)
        next_checker_id = request.data.get('next_checker')
        if next_checker_id is not None:
            try:
                next_checker = User.objects.get(pk=next_checker_id)
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_400_BAD_REQUEST)
            contract.next_checker = next_checker
        else:
            contract.next_checker = None

        contract.save(update_fields=['step','is_effective','next_checker'])
        content_type = ContentType.objects.get_for_model(contract)
        Check.objects.create(
            content_type=content_type, object_id=contract.id,
            check_user=self.request.user, opinion=self.request.data.get('opinion', ''),
            is_agree=self.request.data.get('is_agree', True)
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(detail=False, methods=['post'])
    def delete_selected(self, request):
        """删除所选"""
        selected_ids = request.data['selected_ids']
        deleted_count = Contract.objects.filter(id__in=selected_ids).update(del_flag=True)
        result={"status": "success", "deleted_count": deleted_count}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeModify(self, request, *args, **kwargs):
        """待我修改"""
        query =Q(updater=self.user) & Q(is_effective=-1) & Q(del_flag=0)
        queryset = Contract.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['get'])
    def waitMeCheck(self, request, *args, **kwargs):
        """待我审核"""
        query =Q(next_checker=self.user) & Q(is_effective=0) & Q(del_flag=0)
        queryset = Contract.objects.filter(query)
        result = queryset.aggregate(
            total_count=Count('name')
        )
        return Response(data=result, status=status.HTTP_200_OK)




class BusinessOpportunitySigning_PredictionViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """签约预测"""
    serializer_class = BusinessOpportunitySigning_PredictionSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated, PbiPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = BusinessOpportunityFilter
    search_fields = ['number', 'name']
    select_related_fields = ['company', 'signing_forecast_person','updater']
    ordering_fields = ['id', 'number', 'name']

    def get_queryset(self):
        base_query = Q(del_flag=False) & (Q(project_status='pbi0009_001') | Q(project_status='pbi0009_002'))
        # 根据权限添加额外的查询条件
        if "pbi_view_qs" not in self.request.user.permissions:
            base_query &= Q(company=self.request.user.company)
        business_opportunities = BusinessOpportunity.objects.filter(base_query)
        return business_opportunities


    def list(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        statistic = queryset.aggregate(count=Count('id'),
                                       total_budget=Sum('budget'),
                                       total_project_amount=Sum('project_amount'),
                                       )
        serializer = self.get_serializer(queryset, many=True)
        data={
            "count": statistic['count'],
            "total_budget": round(statistic['total_budget']/10000, 2) if statistic['total_budget'] is not None else 0,
            "total_project_amount": round(statistic['total_project_amount']/10000, 2) if statistic['total_project_amount'] is not None else 0,
            "results":serializer.data
        }
        return Response(data=data, status=status.HTTP_200_OK)


